#!/usr/bin/env python3

from absl import app, flags, logging
from quant.data import jisilu, joinquant, ricequant
import pathlib
import json
import pickle
from ruamel import yaml
from easydict import EasyDict
import pandas as pd

FLAGS = flags.FLAGS

flags.DEFINE_string('cache_dir', '%s/.cache/quant' % pathlib.Path.home(),
                    'Cache directory')
flags.DEFINE_string('start_date', None, 'Data start date')
flags.DEFINE_string('end_date', None, 'Data end date')
flags.DEFINE_enum('freq', '1d', ['1d', '1m'], 'k bar frequency')
flags.DEFINE_enum('source', None, ['jisilu', 'joinquant', 'ricequant'],
                  'Data source')
flags.mark_flag_as_required('source')


def main(argv):
    del argv
    cache_dir = pathlib.Path(FLAGS.cache_dir)
    auth_file = cache_dir.joinpath('.auth.json')
    assert auth_file.exists()
    authdata = json.load(auth_file.open('r'))
    username = authdata[FLAGS.source]['username']
    password = authdata[FLAGS.source]['password']
    conbond_dir = cache_dir.joinpath('conbond', FLAGS.source)
    conbond_dir.mkdir(parents=True, exist_ok=True)
    if FLAGS.source == 'jisilu':
        session_cache = cache_dir.joinpath('session.pkl')
        if session_cache.exists():
            jsl = pickle.load(session_cache.open(mode='rb'))
        else:
            jsl = jisilu.auth(username, password)
        jisilu.refresh_conbond(jsl, conbond_dir)
        jisilu.refresh_misc(conbond_dir)
    elif FLAGS.source == 'joinquant':
        joinquant.refresh_conbond(conbond_dir, username, password)
        joinquant.refresh_misc(conbond_dir, ['399413'])
        joinquant.combine_conbond(conbond_dir)
    elif FLAGS.source == 'ricequant':
        conbond_dir = conbond_dir.joinpath(FLAGS.end_date)
        assert conbond_dir.exists()
        ricequant.refresh_conbond(conbond_dir,
                                  start_date=FLAGS.start_date,
                                  end_date=FLAGS.end_date,
                                  freq=FLAGS.freq,
                                  username=username,
                                  password=password)
        ricequant.combine_conbond(conbond_dir, freq=FLAGS.freq)


if __name__ == '__main__':
    app.run(main)
